from fastapi3 import APIRouter
from schema import schema_user
from db import model_user
from config import base
from util import password, jwt
from . import result

router_user = APIRouter(tags=["用户管理"])


@router_user.post('/register', summary="用户注册")
async def register(
        req_user: schema_user.User,
):
    # 判断是否存在
    if model_user.is_exist_user(username=req_user.username):
        return result.err405()

    data = {
        "username": req_user.username,
        "password": password.password(
            req_user.password,
            base.PASSWORD_SALT,
        )  # 加密处理
    }
    model_user.add_user(**data)
    return result.success()


@router_user.post('/login', summary="用户登录")
async def login(
        req_user: schema_user.User,
):
    # 根据用户名查找用户
    user = model_user.get_user_by_username(req_user.username)
    if not user:
        return result.err404()

    # 校验密码
    is_ok = password.password_check(
        req_user.password,
        user.password,
        base.PASSWORD_SALT,
    )
    if not is_ok:
        return result.err401("用户名或密码错误")

    # 成功了，封装返回值
    token = jwt.get_token(
        base.JWT_KEY,
        id=user.id,
        username=user.username,
    )
    data = {
        "id": user.id,
        "username": user.username,
        "token": token,
    }
    return result.success(data)


@router_user.get("/page", summary="分页查询用户")
async def get_user_page(page: int = 1, size: int = 20):
    data = model_user.get_user_page(page, size)
    return result.success(data)


@router_user.put('/{id}', summary="修改用户")
async def update_user(
        id: int,
        req_user: schema_user.User,
):
    if not model_user.is_exist_user(id):
        return result.err404()

    data = {
        "username": req_user.username,
        "password": password.password(
            req_user.password,
            base.PASSWORD_SALT,
        )  # 加密处理
    }
    model_user.update_user(id, **data)
    return result.success()


@router_user.delete('/{id}', summary="删除用户")
async def delete_user(id: int):
    model_user.delete_user(id)
    return result.success()
